package zcj.stu;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class C30 {
    public static void main(String[] args) throws Exception{
        //case1
        ExceptionHandlerExceptionResolver exceptionResolver=new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMessageConverters(List.of(new MappingJackson2HttpMessageConverter()));
        exceptionResolver.afterPropertiesSet();

        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        HandlerMethod method = new HandlerMethod(new HandleException(), HandleException.class.getMethod("foo"));
        Exception e = new Exception("e0",new RuntimeException("e1",new IOException("e2",new ArrayIndexOutOfBoundsException("i"))));
        exceptionResolver.resolveException(request,response,method,e);
        System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
        //case2
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
        ExceptionHandlerExceptionResolver resolver = context.getBean(ExceptionHandlerExceptionResolver.class);
        HandlerMethod method1 = new HandlerMethod(new HandleException1(), HandleException.class.getMethod("foo"));
        resolver.resolveException(request,response,method1,new ArithmeticException("000"));
        System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
    }
    static class HandleException{
        public void foo(){
            System.out.println("foo,.,");
        }
        @ExceptionHandler()
        @ResponseBody
        public Map<String,String>handleEx(ArrayIndexOutOfBoundsException exception){
                return Map.of("error",exception.getMessage());
        }
    }
    static class HandleException1{
        public void foo(){
            System.out.println("foo,.,");
        }
    }
}
